import { ref } from 'vue';
import { accountService } from '@/services/security/LoginAccount';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Ref } from '@vue/reactivity';

export interface UseUpgradeEmail {
  email: Ref<string | null>;
  password: Ref<string | null>;
  visible: Ref<boolean>;
  handleCloseEmail: () => void;
  confirmCancelEmail: (done: () => void) => void;
  handleUpdateEmail: () => Promise<void>;
  handleDeleteEmail: () => Promise<void>;
}

export const useUpgradeEmail = (refresh: () => void): UseUpgradeEmail => {
  const email = ref(null as string | null);
  const password = ref(null as string | null);
  const visible = ref(false);

  const handleCloseEmail = () => {
    password.value = null;
    email.value = null;
    visible.value = false;
    refresh();
  };

  const confirmCancelEmail = (done: () => void) => {
    ElMessageBox.confirm('确认关闭？')
      .then(() => {
        password.value = null;
        email.value = null;
        done();
      })
      .catch(() => {})
      .finally(refresh);
  };

  const handleUpdateEmail = async () => {
    try {
      await accountService.upgradeEmail(password.value as string, email.value as string);
    } catch (e) {
      ElMessage.error((e as Error).message);
    } finally {
      handleCloseEmail();
    }
  };

  const handleDeleteEmail = async () => {
    try {
      await accountService.deleteEmail();
    } catch (e) {
      ElMessage.error((e as Error).message);
    } finally {
      refresh();
    }
  };
  return {
    email,
    password,
    visible,
    handleCloseEmail,
    confirmCancelEmail,
    handleUpdateEmail,
    handleDeleteEmail,
  };
};
